package com.swsc.xapp.utils;

import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.swsc.xapp.enums.NJSFEnums;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author chencl
 * @Date 2022/4/17 23:42
 * @Version 1.0
 * @Description 本地缓存数据读写 NFS_: native file store, NFR_: native file read
 * @see NativeJSUtils
 */
public class NativeJSUtils {


    // file:///storage/emulated/0/FlygoData
    public static final String BASE_DIR = ConstantUils.DIR_BASE;
    private static String TAG = NativeJSUtils.class.getSimpleName();

    public static void saveBaseUrlInfo(String baseUrlInfoStr){
        writeString2File(BASE_DIR.concat(NJSFEnums.NFS_BASE_URL.getExtra()), baseUrlInfoStr);
    }

    public static JSONObject readBaseUrlInfo(){
        String str = readFile2String(NJSFEnums.NFS_BASE_URL.getExtra());
        return JSONObject.parseObject(str);
    }

    public static String readFile2String(String fileName){
        if(!fileName.contains(BASE_DIR)){
            fileName = BASE_DIR.concat(fileName);
        }
        String result = null;
        try(InputStream in = new FileInputStream(fileName);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
            copyLarge(in, baos, new byte[4096]);
            result = new String(baos.toByteArray(), "UTF-8");
        } catch (FileNotFoundException e) {
            Log.e(TAG, "找不到文件", e);
        } catch (IOException e) {
            Log.e(TAG, "读文件异常", e);
        }
        return result;
    }

    public static JSONObject saveGlobalUrl(String apiUrl, String fileUrl, String tileUrl){
        JSONObject jsonObject = readCacheGlobalUrl();
        if(null == jsonObject){
            jsonObject = new JSONObject();
        }
        if(null != apiUrl || !"".equals(apiUrl.trim())){
            jsonObject.put(ConstantUils.CK_GLOBAL_API_URL, apiUrl);
        }
        if(null != fileUrl || !"".equals(fileUrl.trim())){
            jsonObject.put(ConstantUils.CK_GLOBAL_FILE_URL, fileUrl);
        }
        if(null != tileUrl || !"".equals(tileUrl.trim())){
            jsonObject.put(ConstantUils.CK_GLOBAL_TILE_URL, tileUrl);
        }
        writeString2File(NJSFEnums.NFS_BASE_URL.getExtra(), jsonObject.toString());
        return jsonObject;
    }

    public static JSONObject readCacheUserInfo(){
        return readJsonObjectFromCache(NJSFEnums.NFR_USERINFO.getExtra());
    }
    public static JSONObject readCacheGlobalUrl(){
        return  readJsonObjectFromCache(NJSFEnums.NFS_BASE_URL.getExtra());
    }

    public static JSONObject readJsonObjectFromCache(String fileName){
        String content = readFile2String(fileName);
        if(null != content && !"".equals(content.trim())){
            return JSONObject.parseObject(content);
        }
        return null;
    }

    public static JSONObject initBaseUrl()  {
        return saveGlobalUrl("http://39.100.42.60/uas/api/", "http://39.100.42.60/swsc/dfs/", "http://39.100.42.60/swsc/tiles/");
    }

    public static void writeString2File(String fileName, String content){
        checkBaseDir(BASE_DIR);
        if(!fileName.contains(BASE_DIR)){
            fileName = BASE_DIR.concat(fileName);
        }

        checkFile(fileName);
        try (FileOutputStream fos = new FileOutputStream(fileName)){
            fos.write(content.getBytes());
            fos.flush();
        } catch (FileNotFoundException e) {
            Log.e(TAG, "找不到文件", e);
        } catch (IOException e) {
            Log.e(TAG, "写文件异常", e);
        }


    }

    public static void checkFile(String fileName){
        File file = new File(fileName);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                Log.e(TAG, "创建文件失败", e);
                return;
            }
        }
    }

    public static void checkFileParentDir(File file){
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
    }

    public static void checkBaseDir(String dir){
        File file = new File(dir);
        if(!file.exists()){
            boolean flag = file.mkdirs();
            if(!flag){
                Log.e(TAG, "创建目录失败");
            }
        }
    }

    public static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
            throws IOException {
        long count = 0;
        int len = 0;
        while (-1 != (len = input.read(buffer))) {
            output.write(buffer, 0, len);
            count += len;
        }
        return count;
    }
}
